package com.cloud.service;

import com.cloud.mapper.CartGoodsMapper;
import com.cloud.mapper.OrdersMapper;
import com.cloud.pojo.CartGoods;
import com.cloud.pojo.Orders;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@DubboService
public class OrdersServiceImpl implements OrdersService {
  @Autowired
  private OrdersMapper ordersMapper;
  @Autowired
  private CartGoodsMapper cartGoodsMapper;
  @Autowired
  private RocketMQTemplate rocketMQTemplate;
  private final String CHECK_ORDERS_QUEUE= "check_orders_queue";


  @Override
  public Orders add(Orders orders) {
    // 订单状态未付款
    if (orders.getStatus() == null){
      orders.setStatus(1);
    }
    // 订单创建时间
    orders.setCreateTime(new Date());
    // 计算订单价格
    List<CartGoods> cartGoods = orders.getCartGoods();
    BigDecimal sum = BigDecimal.ZERO;
    for (CartGoods cartGood : cartGoods) {
      BigDecimal num = new BigDecimal(cartGood.getNum()); // 数量
      BigDecimal price = cartGood.getPrice(); // 单价
      BigDecimal multiply = num.multiply(price);
      sum = sum.add(multiply);
    }
    orders.setPayment(sum);
    // 保存订单
    ordersMapper.insert(orders);
    // 将订单商品（购物车商品）保存到数据库中
    for (CartGoods cartGood : cartGoods) {
      cartGood.setOrderId(orders.getId());
      cartGoodsMapper.insert(cartGood);
    }
    return orders;
  }




  @Override
  public Orders findById(String id) {
    return ordersMapper.findById(id);
  }


  @Override
  public List<Orders> findUserOrders(Long userId,Integer status) {
    return ordersMapper.findOrdersByUserIdAndStatus(userId,status);
  }


  @Override
  public void update(Orders orders) {
    ordersMapper.updateById(orders);
  }

}
